﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using SerialPortSim.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SerialPortSim.ViewModels
{
    public partial class MainWindowViewModel : ObservableObject
    {
        public MainWindowViewModel()
        {
            InitBaudrate();
            UpdatePort();
            serialPort1 = new SerialPort();
            ConnectbtnContent = "连接";
            SeteledBaudrate = 115200;
            IsCommboxEnable = !serialPort1.IsOpen;
        }
        



        [ObservableProperty]
        private string? title;

        [ObservableProperty]
        private int seteledBaudrate;

        [ObservableProperty]
        private ObservableCollection<string> comports;

        [ObservableProperty]
        private string? seletedport;

        [ObservableProperty]
        private ObservableCollection<int> baudRates;

        [ObservableProperty]
        private string connectbtnContent;

        [ObservableProperty]
        private bool isCommboxEnable;



        public SerialPort serialPort1;

         

        [RelayCommand]
        private void UpdatePort()
        {
            string[] ports = SerialPort.GetPortNames();
            if (Comports == null)
            {
                Comports = new ObservableCollection<string>();
            }
            Comports.Clear();
            foreach (string port in ports)
            {
                Comports.Add(port);
            }
        }

        [RelayCommand]
        private void ConnectPort()
        {

        }


        void InitBaudrate()
        {
            if (BaudRates == null)
            {
                BaudRates = new ObservableCollection<int>();
            }
            BaudRates.Clear();
            BaudRates.Add( 4800 );
            BaudRates.Add( 9600 );
            BaudRates.Add( 19200 );
            BaudRates.Add( 38400 );
            BaudRates.Add( 57600 );
            BaudRates.Add( 115200);
            BaudRates.Add( 230400);
        }


        private void StartListening()
        {
            try
            {
                if (serialPort1 != null && serialPort1.IsOpen)
                {
                    serialPort1.Dispose();
                    serialPort1.Close();
                   // BatSerialPort.Instance.IsSendThreadRun = false;
                    // logger.Log(LogLevel.Debug, "SerialPort.Dispose() & SerialPort.Close() are executed on StartListening() method.");
                }

                serialPort1.PortName =Seletedport;
                serialPort1.BaudRate = SeteledBaudrate;
                serialPort1.Parity = Parity.None;
                serialPort1.DataBits = 8;
                serialPort1.StopBits = StopBits.One;
                serialPort1.Open();
                serialPort1.DtrEnable = false;
                serialPort1.RtsEnable = false;
                serialPort1.DataReceived += new SerialDataReceivedEventHandler(BatSerialPort.Instance.DataReceivedEvent);
                UpdateBtnConnectStr();
                BatSerialPort.Instance.IsSendThreadRun = true;
                BatSerialPort.Instance.Sendtask();
                BatSerialPort.Instance.RevTsak();
                while (BatSerialPort.Instance.IsSendThreadRun)
                {
                    UpdateBtnConnectStr();
                }
            }
            catch (Exception ex)
            {
                UpdateBtnConnectStr();
                SendMessage($"串口连接失败\r\n{ex.Message}");
            }

        }


        private void UpdateBtnConnectStr()
        {
            if (serialPort1.IsOpen)
            {
                ConnectbtnContent = "断开";
            }
            else
            {
                ConnectbtnContent = "连接";
            }
        }


        public void RevTsak()
        {
            Task.Run(() =>
            {
                BatteryUsartData batteryUsartData = new BatteryUsartData();
                batteryUsartData.Listdata = new List<byte>();
                bool isSucess = false;
                byte tempByte = 0;

                while (IsSendThreadRun)
                {
                    if (revQueue.Count > 0)
                    {
                        if (revQueue.TryDequeue(out tempByte))
                        {
                            isSucess = batteryUsartData.UsartParseData(tempByte);
                            if (isSucess)
                            {
                                if (CurrentData.Instance.IsStopRequestVolt)
                                {
                                    IsRevedData = false;
                                }
                                else
                                {
                                    IsRevedData = true;
                                }

                                MyEventAggregator.Instance.GetEvent<ZrLinkDataAgEvent>().Publish(batteryUsartData);
                                batteryUsartData.Listdata.Clear();
                            }
                        }
                    }
                }
            });
        }

    }
}
